import { createRouter, createWebHashHistory } from 'vue-router';
import { useAuthorizationStore } from '../stores/authorization';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import("../views/HomeView.vue"),
    },
    {
      path: '/admin',
      children: [
        {
          path: '',
          name: 'admin',
          component: () => import("../views/AdminView.vue"),
        },
        {
          path: '/bill/upload',
          name: 'billUpload',
          component: () => import("../views/BillUploadView.vue"),
        },
        {
          path: '/bill/detail',
          name: 'billDetail',
          component: () => import("../views/BillDetailView.vue"),
        },
      ]
    },
    {
      path: '/user',
      children: [
        {
          path: '',
          name: 'user',
          component: () => import("../views/UserView.vue"),
        },
        {
          path: '/document/detail',
          name: 'documentDetail',
          component: () => import("../views/DocumentDetailView.vue"),
        },
      ]
    },
    // {
    //   path: '/test',
    //   name: 'test',
    //   component: () => import("../views/Test.vue"),
    // },
    {
      path: '/note',
      name: 'note',
      component: () => import("../views/NoteView.vue"),
    },
    {
      path: '/course',
      children: [
        {
          path: '',
          name: 'course',
          component: () => import("../views/CourseView.vue"),
        },
        {
          path: '/course/add',
          name: 'addCourse',
          component: () => import("../views/AddCourseView.vue"),
        },
        {
          path: '/course/edit',
          name: 'editCourse',
          component: () => import("../views/EditCourseView.vue"),
        },
      ]
    },
    {
      path: '/material',
      name: 'material',
      component: () => import("../views/MaterialView.vue"),
    },
    {
      path: '/login',
      name: 'login',
      component: () => import("../views/LoginView.vue"),
    },
    {
      path: '/register',
      name: 'register',
      component: () => import("../views/RegisterView.vue"),
    },
    {
      path: '/music',
      name: 'music',
      component: () => import("../views/MusicView.vue"),
    },
  ]
})

router.beforeEach(async (to, from, next) => {
  const { authorization } = useAuthorizationStore(); // 获取 Pinia store 实例
  console.log(authorization);
  if (!authorization && to.name !== 'login' && to.name !== 'register') {
    next({ path: '/login' });
  } else {
    next();
  };
  // userStore.
  // if (
  //   // 检查用户是否已登录
  //   !isAuthenticated &&
  //   // ❗️ 避免无限重定向
  //   to.name !== 'Login'
  // ) {
  //   // 将用户重定向到登录页面
  //   return { name: 'Login' }
  // }
})

export default router;
